<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\car;


use app\dao\car\BasePlaceDao;
use app\model\car\BaseCity;
use app\model\car\BasePlace;
use app\model\car\BaseSendFee;
use app\model\car\CarHoliday;
use app\model\car\CarTypeInfo;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use app\model\car\CarStaff;
use app\dao\car\CarStaffDao;
use think\facade\Db;

/**
 * Class BasePlaceServices
 * @package app\services\shendeng
 */
class BasePlaceServices extends BaseServices
{
    public function __construct(BasePlaceDao $dao,CarStaffDao $dao2)
    {
        $this->dao = $dao;
        $this->dao2 = $dao2;
    }

    /**
     * 列表
     * @param array $where
     * @param bool $is_page
     * @return array
     */
    public function getList(array $where = [],bool $is_page = false){
        $page = $limit = 0;
        if($is_page) [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getList($where,$page,$limit);
        return $list;
    }

    /**
     * 添加/修改
     * @param int $id
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(int $id,array $data){
        $place = $this->dao->getOne(['title'=>$data['title'],'is_del'=>0]);
        $latlng = explode(',',$data['latlng']);
        if(count($latlng)<2){
            throw new AdminException('请正确选择经纬度');
        }
        if((int)$latlng[0] == 0 || (int)$latlng[1] == 0){
            throw new AdminException('请正确选择经纬度');
        }
        $data['latitude'] = $latlng[0];
        $data['longitude'] = $latlng[1];
        $data['start_time'] = $data['start_time'].':00';
        $data['end_time'] = $data['end_time'].':00';
        if($data['start_time'] > $data['end_time']){
            throw new AdminException('结束时间不能小于开始时间');
        }
        if($id){
            if(!$this->dao->get($id)) throw new AdminException('数据不存在');
            if($place && $id != $place['id']) throw new AdminException('地点已存在');
            if($this->dao->update($id,$data)){
                return true;
            } else {
                throw new AdminException('修改失败或您没有修改什么');
            }
        } else {
            unset($data['id']);
            if($place) throw new AdminException('该地点已存在');
            $data['add_time'] = time();
            if($get_id = $this->dao->save($data)){
                //添加默认店员账号
                $check = $this->dao2->getOne(['login_name'=>$data['login_name'],'is_del'=>0]);
                if(isset($data['pwd'])&&$data['pwd']){
                    $data['pwd'] = md5($data['pwd']);
                }else{
                    unset($data['pwd']);
                }
                $data['place_id'] = $get_id->id;
                if ($check) throw new AdminException('店员账号名称已存在');
                    $data['add_time'] = time();
                    if($this->dao2->save($data)){
                        return '添加成功';
                    }else{
                        throw new AdminException('添加失败');
                    }
                //添加默认店员账号

                return true;
            } else {
                throw new AdminException('添加失败');
            }
        }
    }

    /**
     * 地点删除
     * @param int $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delPlace(int $id){
        $city = $this->dao->get($id);
        if ($city) {
            $data['is_del'] = 1;
            $data['delete_time'] = time();
            if (!$this->dao->update($id,$data)) {
                throw new AdminException('删除失败,请稍候再试!');
            }
            //删除门店下面的账号
            Db::name('car_staff')->where('place_id',$id)->update($data);
        }
        return '删除成功!';
    }

    /**
     * 显示/隐藏
     * @param int $id
     * @param int $status
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setShow(int $id, int $status){
        $city = $this->dao->getOne(['id' => $id,'is_del'=>0]);
        if (!$city)
            throw new AdminException('数据不存在');
        if ($this->dao->update($id, ['status' => $status])) {
            return $status == 1 ? '显示成功' : '隐藏成功';
        } else {
            throw new AdminException($status == 1 ? '显示失败' : '隐藏失败');
        }
    }

    /**
     * 地点详细
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo(int $id){
        $place = $this->dao->getOne(['id'=>$id,'is_del'=>0])->toArray();
        if(!$place) throw new AdminException('数据不存在');
        $place['latlng'] = $place['latitude'] . ',' . $place['longitude'];
        return $place;
    }

    /**
     * 获取地点级联数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function placeCascader(){
        $city = BaseCity::field('id,city_name')->where('is_del',0)->select()->toArray();
        $data = [];
        $i = 0;
        foreach ($city as $cityItem){
            $place = BasePlace::field('id,title')->where(['city_id'=>$cityItem['id'],'is_del'=>0,'status'=>1])->select()->toArray();
            if($place){
                array_push($data,['value'=>$cityItem['id'],'label'=>$cityItem['city_name'],'children'=>[]]);
                foreach ($place as $placeItem){
                    array_push($data[$i]['children'],['value'=>$placeItem['id'],'label'=>$placeItem['title']]);
                }
                $i++;
            }
        }
        return $data;
    }

    /**
     * 门店下拉列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function selectPlaceList($where){
        $place = BasePlace::where($where)->select()->toArray();
        $select = [];
        foreach ($place as $item){
            $select[] = ['value'=>$item['id'],'label'=>$item['title']];
        }
        return $select;
    }

    /**
     * 获取门店
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStoreList(){
        return BasePlace::field('id as value,title as label')
            ->where(['is_del'=>0,'store_id'=>0])
            ->select()->toArray();
    }

    /**
     * 获取门店2
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getStoreList2(){
        return BasePlace::field('id as value,name as label')
            ->where(['is_del'=>0,'store_id'=>0])
            ->select()->toArray();
    }

    /**
     * 获取对应城市下的门店车型信息
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCarShopList($data){
        // 车辆信息
        $car = CarTypeInfo::where(['id'=>$data['type_info_id'],'is_del'=>0])->select()->toArray();
        /** @var CarInfoServices $carInfoServices */
        $carInfoServices = app()->make(CarInfoServices::class);
        if(!$car) return $car;
        // 获取车型门店信息
        $model = new BasePlace();
        $model = $model->alias('p');
        $model = $model->join('car_type t','t.place_id=p.id','left');
        $model = $model->field('p.id,p.title,p.short_desc,t.id as type_id,t.price_hour,t.price,t.sat_price,t.sun_price,p.title as store_title');
        $model = $model->where([['p.is_del','=',0],['t.is_del','=',0],['p.place_type','=',0],['p.city_id','=',$data['city_id']],['t.type_info_id','=',$data['type_info_id']]]);
        $list = $model->select()->toArray();
        $long_km = get_distance($data['take_latitude'],$data['take_longitude'],$data['return_latitude'],$data['return_longitude'],2);
        foreach ($list as &$item){
            // 车辆库存
            $car_info = $carInfoServices->getCarInventory($item['type_id'],$data['stat_time'],$data['end_time']);
            $item['inventory'] = $car_info['inventory'];
            $item['car_no'] = $car_info['car_no'];
            $time = strtotime('-90 day',strtotime(date('Y-m-d',time())));
            // 判断是否假期
            $holiday = CarHoliday::where(['store_id'=>$item['id'],'is_del'=>0])->where('begin_time','>=',$time)->select()->toArray();
            $item['is_holiday'] = false;
            foreach ($holiday as $val){
                if($data['stat_time'] >= $val['begin_time'] && $data['stat_time'] <= $val['end_time'] || $data['end_time'] >= $val['begin_time'] && $data['end_time'] <= $val['end_time']){
                    $item['is_holiday'] = true;
                    break;
                }
            }
            // 是否在配送范围内
//            $sendFee = BaseSendFee::where(['store_id' => $item['id'],'is_del' => 0])->where('mink_km','<=',$long_km)->where('max_km','>',$long_km)->find();
              $sendFee = BaseSendFee::where(['store_id' => $item['id'],'is_del' => 0])->find();
            $item['is_scope'] = (bool)$sendFee;
        }
        return $list;
    }
    public function getPlace($where){
        $place = BasePlace::where($where)->select()->toArray();
        return $place;
    }

    /**
     * 网点列表
     * @param array $where
     * @param bool $is_page
     * @return array
     */
    public function getOutletList(array $where,bool $is_page){
        $page = $limit = 0;
        if($is_page) [$page,$limit] = $this->getPageValue();
        $list = $this->dao->getOutletList($where,$page,$limit,$is_page);
        return $list;
    }

    /**
     * 网点显示-隐藏
     * @param int $id
     * @param int $status
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function switchOutlet(int $id, int $status){
        $info = $this->dao->get($id);
        if (!$info) throw new AdminException('数据不存在');
        if ($this->dao->update($id, ['status' => $status])) {
            return $status == 1 ? '显示成功' : '隐藏成功';
        } else {
            throw new AdminException($status == 1 ? '显示失败' : '隐藏失败');
        }
    }

    /**
     * 网点添加修改
     * @param int $id
     * @param array $data
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function outletAdd(int $id,array $data){
        $info = $this->dao->getOne(['title'=>$data['title'],'is_del'=>0]);
        $latlng = explode(',',$data['latlng']);
        if(count($latlng)<2) throw new AdminException('请正确选择位置信息');
        if(empty($latlng[0])||empty($latlng[1])) throw new AdminException('请正确选择位置信息');
        $data['latitude'] = $latlng[0];
        $data['longitude'] = $latlng[1];
        $data['start_time'] = $data['start_time'].':00';
        $data['end_time'] = $data['end_time'].':00';
        if($id){
            if(!$info) throw new AdminException('未查询到数据');
            if($id != $info['id']) throw new AdminException('数据已存在');
            if(!$this->dao->update($id,$data)) throw new AdminException('修改失败或你什么也没有修改');
        }else{
            unset($data['id']);
            if($info) throw new AdminException('数据已存在');
            $data['add_time'] = time();
            if(!$this->dao->save($data)) throw new AdminException('添加失败');
        }
        return '提交成功';
    }

    /**
     * 网点删除
     * @param int $id
     * @return string
     */
    public function outletDelete(int $id){
        $res = $this->dao->update($id,['is_del'=>1,'delete_time'=>time()]);
        if(!$res) throw new AdminException('删除失败,请稍候再试');
        return '删除成功';
    }
}
